package com.example.netty.解决拆包粘包问题;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;

/** channelHandle生命周期
 * @author liupk
 * @date 2018/10/24
 */
public class FirstClientHandle extends ChannelInboundHandlerAdapter{
    public FirstClientHandle() {
        super();
    }
    
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel 绑定到线程");
        super.channelRegistered(ctx);
    }
    
    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel 注销绑定");
        super.channelUnregistered(ctx);
    }
    
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("channel 准备就绪");
        for (int i=0 ;i<1000;i++){
            /**获取二进制抽象 ByteBuf*/
            ByteBuf buffer = ctx.alloc().buffer();
            /**讲字符转换为字符集*/
            byte[] bytes = "Netty 牛逼！".getBytes(Charset.forName("utf-8"));
            /**往二进制对象写入字符集*/
            buffer.writeBytes(bytes);
            /**写数据*/
            ctx.channel().writeAndFlush(buffer);
        }
        
    }
    
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel 被关闭");
        super.channelInactive(ctx);
    }
    
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("channel 有数据可读");
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("服务端传回消息"+byteBuf.toString(Charset.forName("utf-8")));
        
        /**继续回传给服务端*/
        ByteBuf buffer = ctx.alloc().buffer();
        byte[] bytes = "服务端回消息拉，你好 吃了吗".getBytes(Charset.forName("utf-8"));
        buffer.writeBytes(bytes);
        ctx.channel().writeAndFlush(buffer);

    }
    
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("当前channel 中数据已经读完");
        super.channelReadComplete(ctx);
    }
    
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.out.println("空闲连接超时触发");
        super.userEventTriggered(ctx, evt);
    }
    
    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel 从可写状态变更时候调用");
        super.channelWritabilityChanged(ctx);
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("发生异常时候调用");
        super.exceptionCaught(ctx, cause);
    }
}